package com.example.smartagrisys.interceptor;

import com.example.smartagrisys.common.ResultCode;
import com.example.smartagrisys.exception.BusinessException;
import com.example.smartagrisys.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT认证拦截器
 */
@Slf4j
@Component
public class JwtAuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${jwt.tokenPrefix}")
    private String tokenPrefix;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        log.info("===== JwtAuthenticationInterceptor.preHandle =====");
        log.info("拦截请求: " + request.getMethod() + " " + request.getRequestURI());
        
        try {
            // 从请求头中获取JWT
            String token = request.getHeader(tokenHeader);
            log.info("Authorization头: " + (token != null ? "长度=" + token.length() : "null"));

            // 判断token是否存在
            if (!StringUtils.hasText(token)) {
                log.warn("未提供token，请求将被拒绝");
                throw new BusinessException(ResultCode.UNAUTHORIZED, "未提供token，请先登录");
            }

            // 判断token格式
            if (!token.startsWith(tokenPrefix)) {
                log.warn("token格式错误，不以" + tokenPrefix + "开头");
                throw new BusinessException(ResultCode.UNAUTHORIZED, "token格式错误");
            }

            // 去除前缀获取token
            token = token.substring(tokenPrefix.length());
            log.info("提取的JWT Token: " + (token.length() > 20 ? token.substring(0, 20) + "..." : token));

            // 验证token
            try {
                if (!jwtUtil.validateToken(token)) {
                    log.warn("token验证失败");
                    throw new BusinessException(ResultCode.UNAUTHORIZED, "token已过期或无效，请重新登录");
                }
                
                // 从token中获取用户信息，并将其设置到请求属性中
                Long userId = jwtUtil.getUserIdFromToken(token);
                String username = jwtUtil.getUsernameFromToken(token);
                String role = jwtUtil.getRoleFromToken(token);
                
                log.info("JWT验证成功 - 用户ID: " + userId + ", 用户名: " + username + ", 角色: " + role);
                
                request.setAttribute("userId", userId);
                request.setAttribute("username", username);
                request.setAttribute("role", role);
                
                return true;
            } catch (Exception e) {
                log.error("JWT验证过程发生异常", e);
                throw new BusinessException(ResultCode.UNAUTHORIZED, "token处理错误: " + e.getMessage());
            }
        } catch (BusinessException be) {
            // 对于业务异常直接抛出
            throw be;
        } catch (Exception e) {
            // 其他异常包装为业务异常
            log.error("JWT拦截器处理过程发生未预期异常", e);
            throw new BusinessException(ResultCode.UNAUTHORIZED, "认证过程发生错误: " + e.getMessage());
        }
    }
} 